from django.db import models

SEX_CHOICE = (
    (0, '女'),
    (1, '男'),
)

# Create your models here.

class Student(models.Model):  #
    # xx = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')
    name = models.CharField(max_length=20, verbose_name='姓名')
    age = models.SmallIntegerField('年龄', null=True)  # null=True允许为空,unique=True唯一
    sex = models.SmallIntegerField('性别', default=0, choices=SEX_CHOICE)  # 0女，1男
    qq = models.CharField('QQ号码', max_length=20, unique=True, default='', error_messages={'unique': 'QQ号码不能重复'})
    phone = models.CharField('电话号码', max_length=20, unique=True, default='')
    c_time = models.DateTimeField('创建时间', auto_now_add=True)  # 自动填充当前时间

    is_delete = models.BooleanField(default=False)  # 记录数据的删除情况

    # 关联字段
    grade = models.ForeignKey('Grade', verbose_name='班级', on_delete=models.SET_NULL, null=True, related_name='students')
    # detail = models.OneToOneField('StudentDetail', on_delete=models.SET_NULL, null=True)
    # on_delete=models.CASCADE级联删除，详情删掉学生信息同步删除
    # on_delete=models.SET_NULL,详情删掉,学生表的detail字段值设置为空，此时必须要设置null=True

    def __str__(self):
        return f'{self.name}-{self.age}'

    class Meta:  # 源
        db_table = 'student'  # 指定表名


class StudentDetail(models.Model):
    num = models.CharField('身份证', max_length=40, unique=True)  # unique=True唯一
    college = models.CharField('毕业学校', max_length=40, default='', null=True)  # default=''设置默认值

    # 关联字段
    student = models.OneToOneField(Student, on_delete=models.CASCADE, related_name='detail')

    def __str__(self):
        return self.college

    class Meta:
        db_table = 's_detail'


class Grade(models.Model):
    name = models.CharField('班级名称', max_length=20)
    num = models.CharField('班期', max_length=20)

    def __str__(self):
        return f'{self.name}-{self.num}'

    class Meta:
        db_table = 's_grade'


class Course(models.Model):
    name = models.CharField('课程名称', max_length=20)
    # students = models.ManyToManyField(Student) # 不需要额外字段
    students = models.ManyToManyField(Student, through='Enroll') #

    def __str__(self):
        return self.name

    class Meta:
        db_table = 's_course'


# 自定义中间表
class Enroll(models.Model):
    course = models.ForeignKey(Course, on_delete=models.CASCADE)
    student = models.ForeignKey(Student, on_delete=models.CASCADE)
    c_time = models.DateTimeField('报名时间', auto_now_add=True)

    class Meta:
        db_table = 's_enroll'